/**
 * StartRegistry.java
 */
package fss;

import java.io.IOException;
import java.rmi.AlreadyBoundException;
import java.rmi.NoSuchObjectException;
import java.rmi.NotBoundException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Scanner;

import fss.remote.FssRegistry;
import fss.remote.ServiceRegistry;
import fss.util.rmi.RmiId;
import fss.util.rmi.RmiUtils;

/**
 * This is a command line utility to start and stop a Service Registry.
 * <p>
 * No need to have the RMI registry running (i.e. via 'rmiregistry' or
 * a utility clasa). Running this class will start the registry for you.
 * 
 * @author thinh
 *
 */
public class StartRegistry {
    private static final String USAGE = "StartRegistry <host> <name>";
    /**
     * @param args
     * @throws IOException 
     * @throws AlreadyBoundException 
     */
    public static void main(String[] args) throws IOException {
        if(args.length != 2) {
            System.out.println("Error: Invalid number of arguments. Expecting 2.");
            System.out.println("Usage: " + USAGE);
            System.exit(-1);
        }
        
        Scanner stdin = new Scanner(System.in);
        String host = args[0];
        String name = args[1];
        Integer port = RmiUtils.getAvailableServiceRegistryPort(host);
        
        if(port == null) {
            System.out.println("All dedicated ports for Service Registry objects are used on localhost (" + host + ").");
            System.exit(1);
        }
        
        RmiId id = new RmiId(host, name, port);
        
        ServiceRegistry server = new FssRegistry(id);
        ServiceRegistry stub = (ServiceRegistry) UnicastRemoteObject.exportObject(server, id.getPort()); 
        Registry registry = LocateRegistry.createRegistry(id.getPort());
        try {            
            try {
                UnicastRemoteObject.unexportObject(stub, true);
            } catch (NoSuchObjectException oe) {
                // ignore
            }
            registry.bind(name, stub);
        } catch (AlreadyBoundException e) {
            registry.rebind(name, stub);
            System.out.println("A rebind took place on remote object with id " + id);
        } 
        System.out.println("******************************************************************");
        System.out.println("Registry started " + id + " on port " + port);        
        System.out.println("Hit enter to remove the Service Registry...");
        System.out.println("******************************************************************");
        stdin.nextLine();        
        try {
            registry.unbind(name);
        } catch (NotBoundException e) {
            // ignore
        }
        System.out.println("Registry unbounded: " + name);
        System.exit(0);
    }
}
